package me.seu.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.entity.Item;
import me.seu.demo.repository.ItemRepository;
import me.seu.demo.service.ElasticsearchServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 往ES中增删改查数据
 *
 * @author liangfeihu
 * @since 2020/4/22 18:44
 */
@Slf4j
@RestController
@RequestMapping("/es/v2")
public class EsCrudV2Controller {

    @Autowired
    ElasticsearchServiceImpl elasticsearchService;

    @GetMapping("/insert/item")
    public ResponseEntity insertEsData() throws Exception {

        Item item = new Item(1L, "小米手机88", "手机",
                "小米", 3699.00, "http://image.baidu.com/13123.jpg");
        elasticsearchService.saveItem(item);
        log.info("[itemRepository.save(item)] success");

        return ResponseEntity.ok("insert elasticsearch item data success");
    }

    @GetMapping("/insert/item/batch")
    public ResponseEntity insertEsDataList() throws Exception {
        List<Item> list = new ArrayList<>();
        list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.baidu.com/13123.jpg"));

        list.add(new Item(4L, "华为Mate20Pro", "手机", "华为", 5199.00, "http://image.baidu.com/13123.jpg"));

        // 接收对象集合，实现批量新增
        //itemRepository.saveAll(list);
        elasticsearchService.saveItems(list);
        return ResponseEntity.ok("insert elasticsearch item batch data success");
    }

    @GetMapping("/delete/item")
    public ResponseEntity deleteEsData(@RequestParam("id") Long id) {

        //itemRepository.deleteById(id);

        return ResponseEntity.ok("delete elasticsearch item data success");
    }

}
